import { createRouter, createWebHashHistory } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies'
const cookies = useCookies()
// 404页面
import NotFound from '@/pages/NotFound.vue'
// 首页
import home from '@/pages/Home.vue'
// 登录
import login from '@/pages/Login.vue'
// 首页
import index from '@/pages/Index/Index.vue'
// 用户管理
import UserList from '@/pages/User/List.vue'
// 商品管理
import GoodsList from '@/pages/Goods/List.vue'
// 商品分类
import GoodsCategory from '@/pages/Goods/Category.vue'
// 订单管理
import OrderList from '@/pages/Order/List.vue'
// banner图
import Banner from '@/pages/Goods/Banner.vue'
// 添加商品
import Commodity from '@/pages/Goods/Commodity.vue'

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  },
  {
    path: '/home',
    name: 'home',
    component: home,
    children: [
      {
        path: '/index',
        name: 'index',
        component: index
      },
      {
        path: '/user/list',
        name: 'UserList',
        component: UserList
      },
      {
        path: '/goods/list',
        name: 'GoodsList',
        component: GoodsList
      },
      {
        path: '/Commodity',
        name: 'Commodity',
        component: Commodity
      },
      {
        path: '/goods/category',
        name: 'Category',
        component: GoodsCategory
      },
      {
        path: '/goods/banner',
        name: 'Banner',
        component: Banner
      },
      {
        path: '/order/list',
        name: 'OrderList',
        component: OrderList
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: login
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const tokenStr = cookies.get('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router